package cn.mesmile.grpc.client;

import cn.mesmile.grpc.demo.Greeting;
import cn.mesmile.grpc.demo.HelloWorldServiceGrpc;
import cn.mesmile.grpc.demo.Person;
import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zb
 * @date 2021/8/9 19:21
 * @Description
 */
@Slf4j
@Service
public class HelloClient {

//    @GrpcClient("local")
//    private Channel serverChannel;

//    public String sendMessage() {
//
//        List<String> strings = Arrays.asList("1", "2", "3");
//        Person person = Person.newBuilder()
//                .setFirstName("第一个性hello ")
//                .setLastName("  world名")
//                .addAllNameList(strings)
//                .build();
//        HelloWorldServiceGrpc.HelloWorldServiceBlockingStub stub = HelloWorldServiceGrpc.newBlockingStub(serverChannel);
//        stub.withDeadlineAfter(3,TimeUnit.MINUTES);
//        Greeting result = stub.sayHello(person);
//        return result.getMessage();
//    }

    @GrpcClient("helloWorldService")
    private HelloWorldServiceGrpc.HelloWorldServiceBlockingStub helloWorldServiceBlockingStub;


    public Greeting sendMessage(String firstName, String lastName, List<String> nameList) {

        Person.Builder builder = Person.newBuilder();
        builder.setFirstName(firstName);
        builder .setLastName(lastName);
        for (String name : nameList) {
            builder.addNameList(name);
        }
        Person person = builder.build();

        log.info("client sending {}", person);

        Greeting greeting = helloWorldServiceBlockingStub.sayHello(person);
        log.info("client received {}", greeting);

        return greeting;
    }

}
